package org.system.core.service.system;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.model.LoginUser;
import org.system.core.enums.UserStatus;
import org.system.core.exception.ServiceException;
import org.system.core.utils.MessageUtils;
import org.system.core.utils.StringUtils;

/**
 * @author baoRoot
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.selectUserByUserName(username);
        if (StringUtils.isNull(user)){
            logger.info("登录用户： {}不存在", username);
            throw new ServiceException(MessageUtils.message("system.user.no_account"));
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            logger.info("登录用户： {}已被删除", username);
            throw new ServiceException(MessageUtils.message("system.user.is_delete"));
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            logger.info("登录用户： {} 已被停用", username);
            throw new ServiceException(MessageUtils.message("system.user.status_off"));
        }
        passwordService.validate(user);
        return createUser(user);
    }

    public UserDetails createUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
